<template>
  <!-- 系统消息 -->
  <view class="message-item system-message" v-if="message._isSystemMsg">
    <view class="system-message-content">
      <text>{{ message.content }}</text>
    </view>
  </view>

  <!-- 普通用户消息 -->
  <view
    class="message-item"
    v-else
    :class="{ 'self-message': isSelf }"
    :id="`msg-${message.oId || index}`"
  >
    <!-- 头像 -->
    <view class="avatar-container" @click="navigateToUserDetail">
      <image
        class="avatar"
        :src="avatarUrl"
        mode="aspectFill"
        @longpress="emitAtUser"
      />
    </view>

    <!-- 消息内容 -->
    <view class="message-content">
      <!-- 用户名 - 仅在他人消息顶部显示 -->
      <view class="username" v-if="!isSelf">
        {{ message.userNickname + "(" + message.userName + ")" || "未知用户" }}
      </view>

      <!-- 系统消息、红包通知或红包领取消息直接显示，不需要气泡 -->
      <view
        v-if="isSystemMessage || isRedPacketMessage || isRedPacketNotice"
        @tap="handleBubbleTap"
        :class="{
          'redpacket-notice-msg': isRedPacketNotice,
          'system-notice-msg': message._isSystemMsg,
        }"
      >
        <text v-if="isRedPacketNotice || message._isSystemMsg">{{
          message.content
        }}</text>
        <rich-text v-else :nodes="renderContent"></rich-text>
      </view>

      <!-- 普通消息气泡 -->
      <view
        v-else
        class="message-bubble"
        @longpress="showMenu"
        @tap="handleBubbleTap"
        hover-class="message-bubble-hover"
        :hover-stay-time="100"
      >
        <!-- 文本消息 -->
        <view class="normal-message" v-if="!isSpecialMessage">
          <rich-text :nodes="renderContent"></rich-text>
        </view>

        <!-- 特殊消息（比如天气、系统通知等） -->
        <view class="special-message" v-else>
          <rich-text :nodes="renderContent"></rich-text>
        </view>

        <!-- 消息底部信息：时间和客户端 -->
        <view class="message-footer">
          <text class="message-time">{{ formatMessageTime }}</text>
          <text class="client-info" v-if="message.client"
            >来自{{ message.client }}</text
          >
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { computed } from "vue";
import { formatDate } from "@/utils/common.js";

const props = defineProps({
  message: {
    type: Object,
    required: true,
  },
  currentUser: {
    type: String,
    default: "",
  },
  currentUserAvatar: {
    type: String,
    default: "https://file.fishpi.cn/default-avatar.png",
  },
  index: {
    type: Number,
    default: 0,
  },
});

const emit = defineEmits([
  "at-user",
  "show-menu",
  "handle-bubble-tap",
  "navigate-to-user",
]);

// 是否是自己发送的消息
const isSelf = computed(() => {
  return props.message.userName === props.currentUser;
});

// 头像URL
const avatarUrl = computed(() => {
  if (isSelf.value) {
    return props.currentUserAvatar;
  }
  return (
    props.message.userAvatarURL || "https://file.fishpi.cn/default-avatar.png"
  );
});

// 检查是否是系统消息
const isSystemMessage = computed(() => {
  return props.message._isSystemMessage || false;
});

// 检查是否是红包消息
const isRedPacketMessage = computed(() => {
  if (!props.message || !props.message.content) return false;

  try {
    if (
      props.message.content.trim().startsWith("{") &&
      props.message.content.trim().endsWith("}")
    ) {
      const jsonData = JSON.parse(props.message.content);
      return jsonData.msgType === "redPacket";
    }
  } catch (e) {
    return false;
  }
  return false;
});

// 检查是否是红包通知
const isRedPacketNotice = computed(() => {
  // 调试日志
  if (props.message._isRedPacketNotice) {
    console.log("检测到红包通知消息:", props.message.content);
  }
  return props.message._isRedPacketNotice === true;
});

// 判断是否为特殊消息类型
const isSpecialMessage = computed(() => {
  // 如果是系统用户或机器人发送的消息
  if (
    props.message.userOId === 0 ||
    (props.message.sysMetal &&
      (props.message.sysMetal.includes("机器人") ||
        props.message.sysMetal.includes("小冰")))
  ) {
    return true;
  }

  // 检查消息内容
  if (props.message.content) {
    try {
      // 首先检查内容是否可能是JSON格式
      if (
        typeof props.message.content === "string" &&
        props.message.content.trim().startsWith("{") &&
        props.message.content.trim().endsWith("}") &&
        (props.message.content.includes('"msgType"') ||
          props.message.content.includes('\\"msgType\\"'))
      ) {
        // 尝试解析JSON
        let jsonContent;
        try {
          jsonContent = JSON.parse(props.message.content);
        } catch (e) {
          // 可能是转义的JSON，尝试二次解析
          try {
            const unescaped = props.message.content.replace(/\\/g, "");
            jsonContent = JSON.parse(unescaped);
          } catch (e2) {
            // 无法解析，仍按关键词判断
          }
        }

        // 如果成功解析为对象，检查msgType
        if (jsonContent && jsonContent.msgType) {
          return true;
        }

        // 关键词判断（兜底方案）
        return (
          props.message.content.includes("redPacket") ||
          props.message.content.includes("weather") ||
          props.message.content.includes("msgType")
        );
      }
    } catch (e) {
      console.log("判断特殊消息时出错", e);
    }
  }

  return false;
});

// 渲染消息内容
const renderContent = computed(() => {
  // 优化：使用防御性判断
  if (!props.message) return "";

  // 红包领取通知直接返回内容
  if (isRedPacketNotice.value) {
    return props.message.content;
  }

  // 获取消息内容
  const content = props.message.content || "";
  if (!content) return "";

  try {
    // 检查是否是特殊消息类型
    if (isSpecialMessage.value) {
      // 如果看起来像JSON，尝试解析
      if (content.trim().startsWith("{") && content.trim().endsWith("}")) {
        try {
          // 使用try-catch解析，避免直接修改原始数据
          const jsonData = JSON.parse(content);

          // 天气消息
          if (jsonData.msgType === "weather" && jsonData.type === "weather") {
            return createWeatherHTML(jsonData);
          }

          // 音乐消息
          if (jsonData.msgType === "music") {
            return createMusicHTML(jsonData);
          }

          // 红包消息
          if (jsonData.msgType === "redPacket") {
            return createRedPacketHTML(jsonData, props.message.oId);
          }

          // 其他JSON消息
          return `<div class="special-content">${content}</div>`;
        } catch (e) {
          console.error("解析JSON消息失败:", e);
          return `<div class="special-content">${content}</div>`;
        }
      }

      // 非JSON特殊消息
      return `<div class="special-content">${content}</div>`;
    }

    // 普通文本消息，直接返回内容
    return content;
  } catch (error) {
    console.error("渲染消息内容失败:", error);
    return content;
  }
});

// 格式化消息时间
const formatMessageTime = computed(() => {
  if (!props.message.time) return "";
  return formatDate(props.message.time, "HH:mm");
});

// 创建天气消息HTML
const createWeatherHTML = (weatherData) => {
  try {
    const dates = weatherData.date ? weatherData.date.split(",") : [];
    const maxTemps = weatherData.max ? weatherData.max.split(",") : [];
    const minTemps = weatherData.min ? weatherData.min.split(",") : [];
    const weatherCodes = weatherData.weatherCode
      ? weatherData.weatherCode.split(",")
      : [];
    const location = weatherData.t || "未知地区";
    const status = weatherData.st || "未知天气";

    let html = `
      <div class="weather-card">
        <div class="weather-header">
          <div class="weather-location">${location}天气</div>
          <div class="weather-status">${status}</div>
        </div>
        <div class="weather-days">`;

    // 添加未来几天天气
    for (let i = 0; i < dates.length && i < 3; i++) {
      const date = dates[i] || `未知`;
      const weatherCode = weatherCodes[i] || "CLOUDY";
      const maxTemp = maxTemps[i] || "?";
      const minTemp = minTemps[i] || "?";

      // 选择天气图标
      let weatherIcon = "☁️"; // 默认阴天
      if (weatherCode.includes("RAIN")) {
        weatherIcon = "🌧️";
      } else if (
        weatherCode.includes("SUNNY") ||
        weatherCode.includes("CLEAR")
      ) {
        weatherIcon = "☀️";
      } else if (
        weatherCode.includes("CLOUDY") &&
        weatherCode.includes("PARTLY")
      ) {
        weatherIcon = "⛅";
      } else if (weatherCode.includes("SNOW")) {
        weatherIcon = "❄️";
      }

      html += `
        <div class="weather-day">
          <div class="weather-date">${date}</div>
          <div class="weather-icon">${weatherIcon}</div>
          <div class="weather-temp">${minTemp}°~${maxTemp}°</div>
        </div>`;
    }

    html += `
        </div>
      </div>`;

    return html;
  } catch (e) {
    console.error("格式化天气消息失败", e);
    return weatherData.t ? `${weatherData.t}天气` : "天气信息";
  }
};

// 创建音乐卡片HTML
const createMusicHTML = (musicData) => {
  try {
    const coverURL =
      musicData.coverURL || "https://file.fishpi.cn/default-music-cover.png";
    const title = musicData.title || "音乐分享";
    const source = musicData.source || "";

    // 创建唯一ID，用于音乐播放器操作
    const musicId = `music_${Date.now()}${Math.floor(Math.random() * 1000)}`;

    // 音乐卡片HTML
    return `
      <div class="music-card" id="${musicId}" data-source="${source}" data-music-id="${musicId}" data-music-title="${title}" data-music-cover="${coverURL}">
        <div class="music-cover">
          <img src="${coverURL}" alt="${title}" />
          <div class="play-icon">▶</div>
        </div>
        <div class="music-info">
          <div class="music-title">${title}</div>
          <div class="music-subtitle">点击播放</div>
        </div>
      </div>
    `;
  } catch (e) {
    console.error("创建音乐卡片失败", e);
    return "音乐分享";
  }
};

// 创建红包消息HTML - 优化展示效果
const createRedPacketHTML = (redPacketData, oId) => {
  // 使用深拷贝而不是直接修改原始对象
  const packetData = JSON.parse(JSON.stringify(redPacketData));
  // 适配历史消息和实时消息的不同字段格式
  // 判断红包状态
  const isOver =
    packetData.isOver ||
    packetData.leftCount === 0 ||
    (packetData.count && packetData.got && packetData.got === packetData.count);

  // 适配历史消息中的got字段（可能是数字）与实时消息中的hasGot（布尔值）
  const hasGot =
    typeof packetData.hasGot !== "undefined" ? packetData.hasGot : false;

  // 适配totalCount和count
  const totalCount = packetData.totalCount || packetData.count || 1;

  // 适配leftCount和got
  let leftCount;
  if (packetData.leftCount !== undefined) {
    leftCount = packetData.leftCount;
  } else if (typeof packetData.got === "number") {
    // 历史消息中got是已领取数量
    leftCount = Math.max(0, totalCount - packetData.got);
  } else if (packetData.got && Array.isArray(packetData.got)) {
    // 实时消息中got是领取记录数组
    leftCount = Math.max(0, totalCount - packetData.got.length);
  } else if (packetData.who && Array.isArray(packetData.who)) {
    // 历史消息中who是领取记录数组
    leftCount = Math.max(0, totalCount - packetData.who.length);
  } else {
    leftCount = totalCount;
  }

  const redPacketId = oId;
  const redPacketType = packetData.type || "normal";

  // 设置不同状态下的样式
  let statusClass = "";
  let statusText = "";

  if (isOver) {
    statusClass = "red-packet-over";
    statusText = "已领完";
  } else if (hasGot) {
    statusClass = "red-packet-got";
    statusText = "已领取";
  } else {
    statusClass = "red-packet-available";
    statusText = `剩余${leftCount}/${totalCount}个`;
  }

  // 红包类型文本
  let typeText = "普通红包";
  if (packetData.type) {
    switch (packetData.type) {
      case "random":
        typeText = "拼手气红包";
        break;
      case "average":
        typeText = "平分红包";
        break;
      case "specify":
        typeText = "专属红包";
        break;
      case "heartbeat":
        typeText = "心跳红包";
        break;
      case "rockPaperScissors":
        typeText = "猜拳红包";
        break;
    }
  }

  // 获取红包金额
  const money = packetData.money || 0;
  const moneyDisplay = money > 0 ? `${money}` : "";

  // 红包消息的HTML
  return `
  <div class="red-packet-card ${statusClass}"
      data-redpacket-id="${redPacketId}"
      data-redpacket-type="${redPacketType}"
      id="redPacket_${redPacketId}"
      style="cursor:pointer;">
    <div class="red-packet-decoration"></div>
    <div class="red-packet-header">
      <div class="red-packet-icon">🧧</div>
      <div class="red-packet-content">
        <div class="red-packet-title">${typeText}</div>
        <div class="red-packet-msg">${
          packetData.msg || "恭喜发财，大吉大利"
        }</div>
      </div>
    </div>
    <div class="red-packet-footer">
      <div class="red-packet-info">
        ${
          moneyDisplay
            ? `<div class="red-packet-money">
          <span class="red-packet-money-value">${moneyDisplay}</span>
          <span class="red-packet-money-unit">积分</span>
        </div>`
            : ""
        }
        <div class="red-packet-status">${statusText}</div>
      </div>
    </div>
  </div>
`;
};

// 导航到用户详情页
const navigateToUserDetail = () => {
  emit("navigate-to-user", props.message.userName);
};

// 长按@用户
const emitAtUser = () => {
  emit("at-user", props.message);
};

// 显示消息菜单
const showMenu = () => {
  console.log("消息长按事件触发，发送show-menu事件:", props.message);

  // 确保消息包含必要的ID
  if (!props.message.oId) {
    console.warn("消息没有oId，可能导致菜单显示问题");
  }

  // 发送事件到父组件，附带完整消息数据
  emit("show-menu", props.message);

  // 提供触觉反馈 (在支持的平台)
  // #ifdef APP-PLUS
  uni.vibrateShort({
    success: function () {
      console.log("振动成功");
    },
  });
  // #endif
};

// 处理消息气泡点击
const handleBubbleTap = (event) => {
  emit("handle-bubble-tap", { event, message: props.message });
};
</script>

<style lang="scss" scoped>
/* 消息项 */
.message-item {
  display: flex;
  margin-bottom: 35rpx;
  position: relative;
  animation: fadeIn 0.3s ease-out;

  @keyframes fadeIn {
    from {
      opacity: 0;
      transform: translateY(10rpx);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }

  &.self-message {
    flex-direction: row-reverse;

    .avatar-container {
      margin-right: 0;
      margin-left: 16rpx;
    }

    .message-content {
      align-items: flex-end;
      margin-right: 0;

      .message-bubble {
        background-color: #007aff;
        border-radius: 20rpx 12rpx 12rpx 20rpx;
        color: #fff;
        box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.15);

        a {
          color: #fff;
          text-decoration: underline;
        }
      }

      .special-message {
        background-color: #f5f5f5;
        color: #333;
      }
    }
  }
}

/* 头像 */
.avatar-container {
  margin-right: 16rpx;
  align-self: flex-start;

  .avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    background-color: #f0f0f0;
    object-fit: cover;
    border: 1px solid rgba(0, 0, 0, 0.05);
  }
}

/* 消息内容 */
.message-content {
  display: flex;
  flex-direction: column;
  max-width: 70%;
  min-width: 100rpx;

  .username {
    font-size: 24rpx;
    color: #999;
    margin-bottom: 8rpx;
  }

  .message-bubble {
    padding: 16rpx 20rpx;
    background-color: #fff;
    border-radius: 12rpx 20rpx 20rpx 12rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
    position: relative;
    word-break: break-word;
  }

  .message-bubble-hover {
    opacity: 0.9;
    background-color: #f9f9f9;
  }
}

.self-message .message-bubble-hover {
  background-color: #0072e8 !important;
}

/* 红包通知消息 */
.redpacket-notice-msg {
  background-color: rgba(255, 87, 51, 0.1);
  color: #ff5733;
  font-size: 24rpx;
  padding: 10rpx 20rpx;
  border-radius: 8rpx;
  text-align: center;
  margin: 10rpx 0;
}

/* 系统消息样式 */
.system-notice-msg {
  color: #666;
  font-size: 24rpx;
  text-align: center;
}

/* 自己发送的消息特殊样式 */
.self-message .message-bubble .message-footer {
  border-top: 1px solid rgba(255, 255, 255, 0.2);
  color: rgba(255, 255, 255, 0.8);

  .client-info {
    color: rgba(255, 255, 255, 0.9);
  }
}

/* 消息底部信息 */
.message-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10rpx;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
  padding-top: 6rpx;
  font-size: 20rpx;
  color: #999;
}

.message-time {
  margin-right: 10rpx;
}

.client-info {
  color: #1890ff;
  max-width: 200rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 天气卡片样式 */
:deep(.weather-card) {
  background: linear-gradient(135deg, #70c1ff, #5c95ff);
  color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
}

:deep(.weather-header) {
  padding: 16rpx 20rpx;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

:deep(.weather-location) {
  font-size: 28rpx;
  font-weight: bold;
}

:deep(.weather-status) {
  font-size: 24rpx;
  opacity: 0.9;
}

:deep(.weather-days) {
  display: flex;
  justify-content: space-around;
  padding: 16rpx 0;
}

:deep(.weather-day) {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
  padding: 10rpx;
}

:deep(.weather-date) {
  font-size: 24rpx;
  margin-bottom: 10rpx;
}

:deep(.weather-icon) {
  font-size: 36rpx;
  margin-bottom: 10rpx;
}

:deep(.weather-temp) {
  font-size: 24rpx;
}

/* 红包样式 */
:deep(.red-packet-card) {
  background: linear-gradient(135deg, #ff4141, #ff1111);
  color: #fff;
  padding: 0;
  border-radius: 16rpx;
  display: flex;
  flex-direction: column;
  box-shadow: 0 8rpx 16rpx rgba(255, 0, 0, 0.2);
  position: relative;
  overflow: hidden;
  width: 400rpx;
  min-width: 400rpx;
}

:deep(.red-packet-decoration) {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 30rpx;
  background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 10" width="100" height="10"><path d="M0 10 L10 0 L20 10 L30 0 L40 10 L50 0 L60 10 L70 0 L80 10 L90 0 L100 10 Z" fill="rgba(255,255,255,0.2)"/></svg>')
    repeat-x;
  background-size: 100rpx 10rpx;
  opacity: 0.5;
}

:deep(.red-packet-header) {
  display: flex;
  align-items: center;
  padding: 20rpx 20rpx 14rpx;
  position: relative;
  border-bottom: 1px dashed rgba(255, 255, 255, 0.2);
}

:deep(.red-packet-icon) {
  font-size: 48rpx;
  margin-right: 14rpx;
  flex-shrink: 0;
  text-shadow: 2rpx 2rpx 8rpx rgba(0, 0, 0, 0.3);
}

:deep(.red-packet-content) {
  flex: 1;
  padding-right: 10rpx;
}

:deep(.red-packet-title) {
  font-size: 22rpx;
  margin-bottom: 4rpx;
  opacity: 0.9;
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
}

:deep(.red-packet-msg) {
  font-size: 28rpx;
  margin-bottom: 4rpx;
  font-weight: bold;
  text-shadow: 1rpx 1rpx 4rpx rgba(0, 0, 0, 0.2);
}

:deep(.red-packet-footer) {
  display: flex;
  flex-direction: column;
  padding: 10rpx 20rpx;
  background-color: rgba(0, 0, 0, 0.1);
}

:deep(.red-packet-info) {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.red-packet-money) {
  display: flex;
  align-items: baseline;
}

:deep(.red-packet-money-value) {
  font-size: 34rpx;
  font-weight: bold;
  color: #ffeb3b;
  text-shadow: 2rpx 2rpx 6rpx rgba(0, 0, 0, 0.3);
  margin-right: 6rpx;
}

:deep(.red-packet-money-unit) {
  font-size: 22rpx;
  color: rgba(255, 255, 255, 0.8);
}

:deep(.red-packet-status) {
  font-size: 22rpx;
  color: rgba(255, 255, 255, 0.9);
  background-color: rgba(0, 0, 0, 0.15);
  padding: 2rpx 10rpx;
  border-radius: 20rpx;
  display: inline-block;
}

/* 红包状态样式 */
:deep(.red-packet-over) {
  background: linear-gradient(135deg, #bb3333, #991111);
  opacity: 0.9;
}

:deep(.red-packet-over::after) {
  display: none; /* 隐藏右上角状态 */
}

:deep(.red-packet-got) {
  background: linear-gradient(135deg, #ff5555, #dd0000);
}

:deep(.red-packet-got::after) {
  display: none; /* 隐藏右上角状态 */
}

:deep(.red-packet-available) {
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
    box-shadow: 0 8rpx 16rpx rgba(255, 0, 0, 0.2);
  }
  50% {
    transform: scale(1.02);
    box-shadow: 0 10rpx 24rpx rgba(255, 0, 0, 0.3);
  }
  100% {
    transform: scale(1);
    box-shadow: 0 8rpx 16rpx rgba(255, 0, 0, 0.2);
  }
}

/* 音乐卡片样式 */
:deep(.music-card) {
  display: flex;
  background: linear-gradient(135deg, #1976d2, #64b5f6);
  border-radius: 16rpx;
  padding: 20rpx;
  margin: 10rpx 0;
  color: #fff;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
  max-width: 600rpx;
  cursor: pointer;
}

:deep(.music-cover) {
  width: 120rpx;
  height: 120rpx;
  border-radius: 10rpx;
  overflow: hidden;
  position: relative;
  margin-right: 20rpx;
}

:deep(.music-cover img) {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

:deep(.play-icon) {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 50rpx;
  height: 50rpx;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 24rpx;
}

:deep(.music-info) {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

:deep(.music-title) {
  font-size: 28rpx;
  font-weight: 500;
  margin-bottom: 10rpx;
  color: #fff;
}

:deep(.music-subtitle) {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
}

/* 普通消息样式 */
.normal-message,
.special-message {
  word-break: break-word;
}

:deep(.normal-message img),
:deep(.special-message img) {
  max-width: 100%;
  max-height: 400rpx;
  object-fit: contain;
  margin: 6rpx 0;
  border-radius: 6rpx;
}

/* 添加系统消息样式 */
.system-message {
  justify-content: center;

  .system-message-content {
    padding: 8rpx 20rpx;
    background-color: rgba(0, 0, 0, 0.05);
    border-radius: 8rpx;
    display: inline-block;

    text {
      font-size: 24rpx;
      color: #666;
    }
  }
}
blockquote {
  font-size: 24rpx;
  padding-left: 12rpx;
  color: #6a737d;
  border-left: 4rpx solid #eaecef;
}
</style>
